package com.ebei.admin.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ebei.admin.mapper.SysDictMapper;
import com.ebei.admin.model.entity.SysDict;
import com.ebei.admin.model.entity.SysDictDetail;
import com.ebei.admin.service.SysDictDetailService;
import com.ebei.admin.service.SysDictService;
import com.ebei.common.constant.CommonConstant;
import com.ebei.common.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * todo 数据字典服务实现类
 *
 * @author crazypenguin
 * @version 1.0
 * @created 2018/4/17
 */
@Service
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements SysDictService {

    @Autowired
    private SysDictDetailService sysDictDetailService;

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = {Exception.class})
    public Result<Boolean> dictDel(Integer dictId) {
        // 删除字典项
        SysDict sysDict = this.selectById(dictId);
        sysDict.setDelFlag(CommonConstant.STATUS_DEL);
        boolean flag1 = this.updateById(sysDict);
        // 同时删除字典项关联详情
        List<SysDictDetail> details = sysDictDetailService.findDictDetailsByDictId(dictId);
        boolean flag2 = true;
        if(details != null && details.size() > 0){
            for(SysDictDetail sysDictDetail : details){
                sysDictDetail.setDelFlag(CommonConstant.STATUS_DEL);
            }
            flag2 = sysDictDetailService.updateBatchById(details);
        }

        Result<Boolean> result = new Result<>();

        if(flag1 && flag2){
            result.setErrorCode(Result.SUCCESS);
            result.setErrorMessage("删除成功");
        }else{
            result.setErrorCode(Result.FAIL);
            result.setErrorMessage("删除失败");
        }

        return result;
    }
}
